<template>
  <div class="item">
    <div class="item-search">
      <el-collapse>
        <el-collapse-item name="1">
          <template slot="title">
            <el-button type="primary">搜索</el-button>
          </template>
          <div class="item-search-input">
            <el-row>
              <el-col :span="4">
                <el-input v-model="searchData.cardNo" placeholder="卡号" class="item-search-input-l"
                          @keyup.enter.native="search"></el-input>
              </el-col>
              <el-col :span="4">
                <el-input v-model="searchData.areaName" placeholder="城市名称" class="item-search-input-l"
                          @keyup.enter.native="search"></el-input>
              </el-col>
              <el-col :span="1">
                <el-button type="primary" icon="search" @click="search"></el-button>
              </el-col>
              <el-col :span="1">
                <el-button type="primary" icon="delete" @click="reset"></el-button>
              </el-col>
            </el-row>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>

    <div class="item-table">

      <div class="item-table-title">
        <h2>{{ tableTitle.big }}<span>{{ tableTitle.small }}</span></h2>
        <div class="item-table-add">
          <el-button type="primary" icon="edit" @click="dialogForm = true">新增卡</el-button>
        </div>
      </div>

      <div class="item-table-main">

        <el-table :data="tableData" border>
          <el-table-column v-for="(item,index) in table" :label="item.label" :key="index"
                           :sortable="item.sortable ? true : false" :prop="item.name">
            <template scope="scope">
              <span :title="scope.row[item.name]">{{ scope.row[item.name] }}</span>
            </template>
          </el-table-column>
        </el-table>

        <div class="item-pagination">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="page.pageNum"
            :page-size="page.pageSize"
            :total="page.total"
            layout="prev, pager, next, jumper, total">
          </el-pagination>
        </div>
      </div>
    </div>

    <!--新增卡号弹窗-->
    <el-dialog v-model="dialogForm" title="新增卡" @close="dialogFormClose" top="70px">
      <div class="item-dialog">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="20%" label-position="left">
           <el-form-item v-for="(item, index) in cardCodeSectionOption" :label="item.label" :key="index">
             <el-select v-model="obj['a' + index]">
               <el-option v-for="(innerItem, innerIndex) in item.value" :key="innerIndex" :label="innerItem.label" :value="innerItem.value"></el-option>
             </el-select>
           </el-form-item>
          <el-form-item prop="areaCode" label="城市">
            <el-cascader v-model="ruleForm.areaCode"  placeholder="请选择城市" :options="provinceCityArea" filterable change-on-select></el-cascader>
          </el-form-item>
          <el-form-item prop="cardNum" label="卡号数">
            <el-input v-model="ruleForm.cardNum"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="ruleForm.remark"></el-input>
          </el-form-item>
          <div class="item-dialog-submit">
            <el-button type="primary" icon="edit" @click="submitForm('ruleForm')">提交</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>

  </div>
</template>

<script type="text/ecmascript-6">
  import { mapState } from 'vuex'
  import ajax from '../../../utils/ajax'

  export default {
    data () {
      return {
        obj: {},
        searchData: { // 搜索字段
          cardNo: '',
          areaName: ''
        },
        dialogForm: false,
        cardCodeSectionOption: [],
        provinceCityArea: [],
        ruleForm: { // 新增卡号字段
          areaCode: [],
          cardNum: '',
          cardTemplate: '',
          remark: ''
        },
        rules: { // 新增表单规则
          areaCode: [
            {required: true, type: 'array', min: 1, message: '请选择城市', toggle: 'blur'}
          ],
          cardNum: [
            {required: true, message: '请填写卡号数量', toggle: 'blur'}
          ]
        }
      }
    },
    computed: mapState({
      tableTitle: state => state.tableTitle,
      table: state => state.table,
      tableData: state => state.tableData,
      page: state => state.page
    }),
    mounted () {
      this.Result()
      this.initCardCodeSectionOption()
      this.initCityOption()
    },
    methods: {
      Result (formData) { // 初始化
        let that = this
        let url = that.$api.insideCard.result
        let store = that.$store

        ajax.get(url, formData || {}, store, true).then((res) => {
          let data = res.data.list
          let page = res.data.page
          store.dispatch('setTableData', data)
          store.dispatch('setPage', page)
        })
      },
      search () { // 搜索
        this.searchData.pageNum = 1
        this.Result(this.searchData)
      },
      reset () { // 清空搜索数据
        this.$clearJson(this.searchData)
      },
      handleCurrentChange (val) { // 分页
        this.searchData.pageNum = val
        this.Result(this.searchData)
      },
      submitForm (formName) { // 新增卡号提交
        let that = this
        let confirm = that.$confirm
        let store = that.$store
        let msg = that.$message
        let url = that.$api.insideCard.addorupdate
        let ruleFormParam = {}
        for (var key in that.ruleForm) {
          ruleFormParam[key] = that.ruleForm[key]
        }
        ruleFormParam.areaCode = ruleFormParam.areaCode.join('/')
        for (var i = 0; i < that.cardCodeSectionOption.length; i++) {
          if (that.obj['a' + i]) {
            // ruleFormParam[that.cardCodeSectionOption[i]] += that.obj['a' + i]
            ruleFormParam.cardTemplate += that.obj['a' + i]
          }
        }
        that.$refs[formName].validate((valid) => {
          if (valid) { // 通过验证
            confirm('是否继续?', '提示', {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'})
              .then(() => {
                store.dispatch('setLoading', true)
                ajax.post(url, ruleFormParam, store).then((res) => {
                  let code = res.msg.code
                  if (code === '20000') {
                    msg({type: 'success', message: '新增成功'})
                    that.Result()
                    that.dialogForm = false
                  } else {
                    msg({type: 'error', message: res.msg.message})
                  }
                  store.dispatch('setLoading', false)
                }).catch((err) => {
                  if (err) throw err
                  store.dispatch('setLoading', false)
                  msg({type: 'error', message: '网络异常'})
                })
              }).catch(() => {})
          } else { // 未通过验证
            console.log('error')
          }
        })
      },
      dialogFormClose () { // 关闭新增弹窗
        this.$refs.ruleForm.resetFields()
        this.$clearJson(this.ruleForm)
      },
      initCardCodeSectionOption () {
        let that = this
        let url = that.$api.insideCard.getCardCodeSection
        let store = that.$store
        ajax.get(url, {}, store, true).then((res) => {
          let data = res.data.dicTrafficInnerCardNoRuleList
          for (var i = 0; i < data.length; i++) {
            let cardCodeSectionData = JSON.parse(data[i].fieldValue)
            let key = data[i].fieldName
            that.cardCodeSectionOption.push({'label': key, 'value': cardCodeSectionData})
            console.log(that.cardCodeSectionOption)
          }
        })
      },
      initCityOption () {
        // 初始化城市选项
        let that = this
        let url = that.$api.insideCard.getCity
        let store = that.$store
        that.provinceCityArea = JSON.parse(localStorage.getItem('cityOption'))
        if (that.provinceCityArea) {
          return false
        }
        ajax.get(url, {}, store, true).then((res) => {
          let code = res.msg.code
          let data = res.data
          console.log(data)
          if (code === '20000') {
            that.provinceCityArea = data
          }
        })
      }
    }
  }
</script>
